//
//  BTContactViewController.m
//  WeChat
//
//  Created by 互联网 on 16/11/3.
//  Copyright © 2016年 bigtree. All rights reserved.
//

#import "BTContactViewController.h"
#import "BTChatViewController.h"

@interface BTContactViewController ()<NSFetchedResultsControllerDelegate>
{
    NSFetchedResultsController *_resultController;
}
@property (nonatomic, strong)NSArray *users;
@end

@implementation BTContactViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadUsers2];
   }
-(void)loadUsers2
{
   NSManagedObjectContext *rosterContext = [BTXMPPTool sharedBTXMPPTool].rosterDataStorage.mainThreadManagedObjectContext;
    
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"XMPPUserCoreDataStorageObject"];
    
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"displayName" ascending:YES];
    fetchRequest.sortDescriptors = @[sort];
    
    NSPredicate *pre = [NSPredicate predicateWithFormat:@" subscription != %@",@"none"];
    fetchRequest.predicate = pre;
    
    // 3.执行请求
    // 3.1 创建结果控制器
    // 数据库查询，如果数据很多，会放在子线程查询
    // 移动客户端的数据不会太多
    _resultController = [[NSFetchedResultsController alloc]initWithFetchRequest:fetchRequest managedObjectContext:rosterContext sectionNameKeyPath:nil cacheName:nil];
    _resultController.delegate = self;
    // 需要执行结果控制器
    NSError *error = nil;
    [_resultController performFetch:&error];
}
-(void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    [self.tableView reloadData];
}
-(void)loadUsers1
{
    // 1.获取上下文,和XMPPRoster.xcdatamode关联
    NSManagedObjectContext *context = [[BTXMPPTool sharedBTXMPPTool].rosterDataStorage mainThreadManagedObjectContext];
    
    // 2.Request 请求查询那张表
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"XMPPUserCoreDataStorageObject"];
    
    // 3.排序
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"displayName" ascending:YES];
    fetchRequest.sortDescriptors = @[sort];
    
    // 4.过滤 ：解决联系人存在
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"订阅 != %@",@"none"];
    fetchRequest.predicate = pre;
    
    // 4.执行请求
    NSError *error = nil;
    NSArray *users = [context executeFetchRequest:fetchRequest error:&error];
    
    self.users = users;
    if (!error) {
        BTLog(@"%@",users);
    }else
    {
        BTLog(@"%@",error);
    }

}

//#pragma mark 当监听的属性发生变化时，调用该方法
//-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
//{
//    BTLog(@"===");
//    BTLog(@"%@",[NSThread currentThread]);
//    [self.tableView reloadData];
//}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    return self.users.count;
    return _resultController.fetchedObjects.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"rosterCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
//    XMPPUserCoreDataStorageObject *users = self.users[indexPath.row];
    XMPPUserCoreDataStorageObject *users = _resultController.fetchedObjects[indexPath.row];

    /**
     *  sectionNum:0：在线 1：离开 2：离线
     */
    BTLog(@"%@  在线状态 %@",users.displayName,users.sectionNum);
    cell.textLabel.text = users.displayName;
    
//    // 方式1：通过KVO监听用户状态的改变
//    [users addObserver:self forKeyPath:@"sectionNum" options: NSKeyValueObservingOptionNew context:nil];
    switch ([users.sectionNum integerValue]) {
        case 0:
            cell.detailTextLabel.text = @"在线";
            break;
        case 1:
            cell.detailTextLabel.text = @"离开";
            break;
        case 2:
            cell.detailTextLabel.text = @"离线";
            break;
        default:
            cell.detailTextLabel.text = @"未知";
            break;
    }
    
    // 显示好友头像
    if (users.photo) { // 默认的情况，不是程序一启动就有头像
        cell.imageView.image = users.photo;
    }else
    { // 如果没有，则通过头像模块从服务器获取
      NSData *imgData = [[BTXMPPTool sharedBTXMPPTool].avatar photoDataForJID:users.jid];
      cell.imageView.image = [UIImage imageWithData:imgData];
    }
    return cell;
}

#pragma mark 实现此方法就会出现delete按钮
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // 删除好友
        // 获取好友
      XMPPUserCoreDataStorageObject *user =  _resultController.fetchedObjects[indexPath.row];
      [[BTXMPPTool sharedBTXMPPTool].roster removeUser:user.jid];
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   XMPPJID *friendJid = [_resultController.fetchedObjects[indexPath.row] jid];
    // 跳转
    [self performSegueWithIdentifier:@"toChatVcSegue" sender:friendJid];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    id VC = segue.destinationViewController;
    if ([VC isKindOfClass:[BTChatViewController class]]) {
        BTChatViewController *chatVc = VC;
        chatVc.friendJid = sender;
    }
}
@end
